package org.shop.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.shop.entity.User;
import org.shop.vo.ErrorVO;

/**
 * 后台管理员登录认证
 * 
 * @author Administrator
 *
 */
@WebFilter("/admin/*")
public class AuthorityFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 向下转型 - 转换为基于HTTP协议的请求和响应对象
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		// 注意：针对login.html页面以及处理登录的login.do这个Servlet必须要进行放行 - 给用户登录机会
		// 1.如何获取用户请求的URL
		// /ch03/admin/login.html
		String uri = req.getRequestURI();

		// http://localhost:9999/ch03/admin/login.html
		// String url = req.getRequestURL().toString();

		// 2.判断放行
		if (uri.endsWith("login.jsp") || uri.endsWith("login.do")) {
			chain.doFilter(req, resp);
			return;
		}

		
		// 3.获取会话对象
		HttpSession session = req.getSession();

		// 4.获取会话中登录的帐号
		User user = (User) session.getAttribute("user");

		// 5.判断是否登录
		// 5.1、登录失败 - 页面跳转到错误提示页面
		if (user == null) {
			ErrorVO error = new ErrorVO("对不起，您没有权限访问","login.jsp");
			request.setAttribute("error", error);
			request.getRequestDispatcher("../error.jsp").forward(request, response);
			return;
		}

		// 5.2、登录成功 - 放行
		chain.doFilter(req, resp);
	}

	@Override
	public void destroy() {

	}

}
